//
//  UIImage+Extension.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import UIKit

extension UIImage {
     
    /**
     根据坐标获取图片中的像素颜色值
     */
    public subscript (x: CGFloat, y: CGFloat) -> UIColor? {
         
        if x < 0 || x > size.width || y < 0 || y > size.height {
            return nil
        }
        guard let cgImage = self.cgImage, let provider = cgImage.dataProvider else {
            return nil
        }
        
        let providerData = provider.data
        guard let data = CFDataGetBytePtr(providerData) else {
            return nil
        }
        
        let numberOfComponents: CGFloat = 4.0
        let pixelData = Int((size.width * y + x) * numberOfComponents)
         
        let r = CGFloat(data[pixelData]) / 255.0
        let g = CGFloat(data[pixelData + 1]) / 255.0
        let b = CGFloat(data[pixelData + 2]) / 255.0
        let a = CGFloat(data[pixelData + 3]) / 255.0
         
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
}
